package com.deepglint.tableapi;

import com.deepglint.beans.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;

/**
 * @author mj
 * @version 1.0
 * @date 2021-11-25 0:02
 */
public class TableTest_Example {
    public static void main(String[] args) throws Exception {
        // 1.创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 2.读取数据
        String path = "C:\\Users\\马军\\Desktop\\Idea-workspace\\flink\\src\\main\\resources\\source.txt";
        DataStreamSource<String> sourceStream = env.readTextFile(path);

        // 3.转换pojo
        SingleOutputStreamOperator<SensorReading> mapStream = sourceStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], split[1], new Long(split[2]), new Double(split[3]));
        });

        // 4.创建表环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 5.基于流创建一张表
        Table table = tableEnv.fromDataStream(mapStream);

        // 6.调用tableAPI进行转换操作
        Table resultTable = table.select("id,temperature").where("id = 'sensor1'");

        // 7. 执行sql
        tableEnv.createTemporaryView("sensor",resultTable);
        String sql = "select id,temperature from sensor where id = 'sensor'";
        Table resultSqlTable = tableEnv.sqlQuery(sql);

         // 8.输出
        tableEnv.toAppendStream(resultTable, Row.class).print("result");
        tableEnv.toAppendStream(resultSqlTable,Row.class).print("sql");

        env.execute();
    }
}
